/**
 * 获取节假日数据
 */

import dayjs from "dayjs";
import useFetch from "./useFetch";
import ApiWork from "@/api/work";

let holidayList: number[];

/**
 * 计算两个时间戳之间的节假日天数
 * @param {number} startTs - 开始时间戳（毫秒）
 * @param {number} endTs - 结束时间戳（毫秒）
 * @param {number[]} holidays - 节假日时间戳数组（毫秒）
 * @returns {number} 节假日天数
 */
function holidayCount(start, end, holidays) {
  let count = 0;

  const startTime = dayjs(start).valueOf();
  const endTime = dayjs(end).valueOf();

  for (const ts of holidays) {
    if (ts >= startTime && ts <= endTime) count++;
  }
  return count;
}

export default (): [
  number[],
  {
    getHolidayCount: typeof getHolidayCount;
  }
] => {
  // 节假日: 秒级时间戳数组
  const { data } = useFetch(ApiWork.getHolidayList, {
    manual: !!holidayList,
    // 返回的是 秒级时间戳
    onAfter: ({ holidayList }: any) =>
      holidayList.map((e) => e.holiday * 1000).sort(),
    onSuccess(list) {
      holidayList = list;
    },
  });

  const list = holidayList || data;

  const getHolidayCount = (start, end) => holidayCount(start, end, list);

  return [
    list,
    {
      getHolidayCount,
    },
  ];
};
